package com.google.code.garbagecan.springdatastudy.mongo;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

public class Test {

	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("/com/google/code/garbagecan/springdatastudy/mongo/spring.xml");

		MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

		mongoOperation.save(new User("1", "kongxx", 30), "users");
		mongoOperation.save(new User("2", "mandy", 30), "users");
		
		List<User> users = null;
		User user = null;
		
		users = mongoOperation.findAll(User.class, "users");
		System.out.println("list user" + users);
		
		user = mongoOperation.findOne(new Query(Criteria.where("id").is("1")), User.class, "users");
		System.out.println("find user : " + user);
		
		user = mongoOperation.findOne(new Query(Criteria.where("id").is("2")), User.class, "users");
		System.out.println("find user : " + user);

		mongoOperation.updateFirst(new Query(Criteria.where("id").is("1")), 
				Update.update("age", 20), "users");
		user = mongoOperation.findOne(new Query(Criteria.where("id").is("1")), User.class, "users");
		System.out.println("find updated user : " + user);
		
		mongoOperation.remove(new Query(Criteria.where("id").is("2")), "users");
		user = mongoOperation.findOne(new Query(Criteria.where("id").is("2")), User.class, "users");
		System.out.println("find removed user : " + user);
		
		users = mongoOperation.findAll(User.class, "users");
		System.out.println("list user" + users);
	}

}
